<?php

namespace App\Service;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;

class CodeService
{
    const EXP_TIME = 60 * 60 * 20;

    public $session;

    public function __construct($session)
    {
        $this->session = $session;
    }

    public function getCode()
    {
        $res = $this->session->get('email_code');
        log_daily('email_code')->info(json_encode($res));
        return $res;
    }

    public function checkCode($code)
    {
        $codeArr = $this->getCode();
        log_daily('email_code')->info('check code '. $code ." " . json_encode($codeArr));
        if (!$codeArr) {
            return [
                'success' => false,
                'msg' => '验证码错误'
            ];
        }
        $preTime = $codeArr['time'];
        if(time() - $preTime > self::EXP_TIME){
            return [
                'success' => false,
                'msg' => '验证码已过期'
            ];
        }
        if($code != $codeArr['code']){
            return [
                'success' => false,
                'msg' => '验证码错误'
            ];
        }
        return [
            'success' => true,
            'msg' => ''
        ];
    }

    public function setCode()
    {
        $code = Str::random(6);
        $arr = [
            'code' => $code,
            'time' => time(),
        ];
        $this->session->put('email_code',$arr);
        log_daily('email_code')->info(json_encode($arr));

        return $code;
    }



}
